import subprocess
import xml.etree.ElementTree as ET
import argparse
import os,stat

def run_gtest_programs(test_programs):
    for program, output_file in test_programs.items():
        cmd = f"{program} --gtest_output=xml:{output_file}"
        try:
            subprocess.run(cmd, check=True, shell=True)
        except Exception:
            print("run {} failed".format(program))

def find_executables(path):
    """查找指定路径下所有的可执行文件"""
    executables = []
    for root, dirs, files in os.walk(path):
        for filename in files:
            file_path = os.path.join(root, filename)
            # 检查文件是否可执行
            if os.access(file_path, os.X_OK):
                executables.append(file_path)
    return executables

if __name__ == "__main__":
    executables = find_executables("Debug/test")
    executables_release = find_executables("Release/test")
    executables.extend(executables_release)
    # 定义gtest程序及其输出文件
    test_programs = {
        # "./test_program_1": "report1.xml",
        # "./test_program_2": "report2.xml",
        # 可以添加更多的测试程序
    }
    for test in executables:
        name = os.path.basename(test)
        test_programs[test]=test+".xml"

    # 运行gtest程序
    run_gtest_programs(test_programs)
    
    print("All tests have been run and the reports have been merged.")
